package com.hex.ds.hdtp.core.app.license.truelicense.service;

import com.hex.ds.hdtp.core.app.license.truelicense.dto.LicenseVerifyParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @Package com.hex.ds.hdtp.core.app.license.truelicense
 * @ClassName LicenseCheckListener
 * @Description 在项目启动时安装证书
 * @Author Yin.Yang
 * @Date 2024/3/27 15:38
 * @Version v1.0
 **/
@Slf4j
@Component
public class LicenseCheckListener {

    /**
     * 证书subject
     */
    @Value("${trueLicense.subject}")
    private String subject;

    /**
     * 公钥别称
     */
    @Value("${trueLicense.publicAlias}")
    private String publicAlias;

    /**
     * 访问公钥库的密码
     */
    @Value("${trueLicense.storePass}")
    private String storePass;

    /**
     * 证书生成路径
     */
    @Value("${trueLicense.licensePath}")
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    @Value("${trueLicense.publicKeysStorePath}")
    private String publicKeysStorePath;

//    @Override
//    public void onApplicationEvent(ContextRefreshedEvent event) {
//        //root application context 没有parent
//        ApplicationContext context = event.getApplicationContext().getParent();
//        if(context==null){
//            if(StringUtils.isNotBlank(licensePath)){
//                log.info("++++++++ 开始安装证书 ++++++++");
//
//                try {
//                    LicenseVerifyParam param = new LicenseVerifyParam();
//                    param.setSubject(subject);
//                    param.setPublicAlias(publicAlias);
//                    param.setStorePass(storePass);
//                    param.setLicensePath(licensePath);
//                    param.setPublicKeysStorePath(publicKeysStorePath);
//
//                    LicenseVerify licenseVerify = new LicenseVerify();
//                    licenseVerify.install(param); // 尝试安装证书
//
//                    log.info("++++++++ 证书安装结束 ++++++++");
//                } catch (Exception e) {
//                    log.error("证书安装失败，应用启动终止！", e);
//                    System.exit(1); // 非 0 状态码表示异常终止
//                }
//            }
//        }
//    }

}
